import type { ComponentInfo, ComponentResolver } from 'unplugin-vue-components';

export interface ElementPlusExtensionResolverOptions {
  directives?: boolean;
  exclude?: RegExp;
}

function resolveComponent(name: string, options: ElementPlusExtensionResolverOptions): ComponentInfo | undefined {
  if (options.exclude && name.match(options.exclude)) {
    return;
  }
  if (!name.match(/^Ex[A-Z]/)) {
    return;
  }
  return {
    name,
    from: `element-plus-extension/es`
  };
}

function resolveDirective(name: string, options: ElementPlusExtensionResolverOptions): ComponentInfo | undefined {
  if (!options.directives) return;

  const directives = ['EllipsisDirective', 'LazyImageDirective', 'PopConfirmDirective', 'TooltipDirective'];
  if (!directives.includes(name)) {
    return;
  }
  return {
    name,
    from: `element-plus-extension/es`
  };
}

export function ElementPlusExtensionResolver(options: ElementPlusExtensionResolverOptions = {}): ComponentResolver[] {
  let optionsResolved: ElementPlusExtensionResolverOptions;

  async function resolveOptions() {
    if (optionsResolved) return optionsResolved;
    optionsResolved = {
      directives: true,
      exclude: undefined,
      ...options
    };
    return optionsResolved;
  }

  return [
    {
      type: 'component',
      resolve: async (name: string) => {
        return resolveComponent(name, await resolveOptions());
      }
    },
    {
      type: 'directive',
      resolve: async (name: string) => {
        return resolveDirective(name, await resolveOptions());
      }
    }
  ];
}
